import React from 'react';
import ListItem from './ListItem';
import { connect } from 'react-redux';
import { FilterTypes } from './../../constants';

class ToDoList extends React.Component {

    constructor(props, context) {
        super(props, context);
        this.state = {
            list: props.list
        }
    }

    componentWillReceiveProps(nextProps) {
        console.error("componentWillReceiveProps");
        console.error(nextProps);
        this.setState({
            list: nextProps.list
        });
    }

    render() {
        console.error("list render");
        console.error("222222222222222222222222222");
        console.error(this.state.list);
        return (
            <ul>
                {
                    this.state.list.map((item) => (
                    
                        <ListItem key={ item.id } id={item.id} text={ item.text } completed={item.completed} />
                    ))
                
                }
            </ul>
        )
    }
}

const mapStateToProps = (state) => {
    console.error("list mapStateToProps");
    console.error(state);
    console.error(state.list);
    console.error(state.filter);
    switch(state.filter) {
        case FilterTypes.ALL:
            console.error(state.list);
            return {
                list: state.list
            }
        case FilterTypes.COMPLETED:
            return {
                list: state.list.filter((item) => {
                    return item.completed ? item : null;
                })
            }
        case FilterTypes.UNCOMPLETED:
            return {
                list: state.list.filter((item) => {
                    return !item.completed ? item : null;
                })
            }
    }
}  

export default connect(mapStateToProps, null)(ToDoList);